//
//  IMPOAuthViewController.swift
//  MySina
//
//  Created by imppppp on 16/5/24.
//  Copyright © 2016年 IMP. All rights reserved.
//

import UIKit
import SVProgressHUD

class IMPOAuthViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        loadOAuth()
    }
    
    
    
    // 在loadView阶段将视图替换为webView
    let webView = UIWebView()
    override func loadView() {

        view = webView
        webView.delegate = self
    }
    
    
    
    
    
}


// MARK: - 设置导航栏
extension IMPOAuthViewController {
    

    
    private func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "close", style: .Plain, target: self, action: #selector(closeBtnClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(autoFillBtnClick))
    }
    
    
    @objc private func closeBtnClick() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillBtnClick() {
        
        let jsString = "document.getElementById('userId').value='15763942442';document.getElementById('passwd').value='2.21WSYxvv'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
}

// MARK: - 打开授权页面
extension IMPOAuthViewController {
    
    private func loadOAuth() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "4102120147" + "&redirect_uri=" + "https://www.baidu.com"
        
        let url = NSURL(string: urlString)
        let req = NSURLRequest(URL: url!)
        webView.loadRequest(req)
    }
    
}


// MARK: - UIWebViewDelegate
extension IMPOAuthViewController: UIWebViewDelegate {
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //授权成功之后 就会回调新页面  在回调页面的地址中会包含code(授权码)
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        print(urlString)
        
        let successFlag = "code="
        if urlString.containsString(successFlag) {
            // 获取授权码
            let range = urlString.rangeOfString(successFlag)
            let subString = urlString.substringFromIndex((range?.endIndex)!)
            print(subString)
            //获取code 之后 应该使用 code码 请求token(用户访问令牌)
        }
        
        
        return true
    }
    
    
}











